package com.dcm.seckill.service.impl;

import com.dcm.common.constant.Constants;
import com.dcm.common.exception.MyException;
import com.dcm.seckill.mapper.SeckillShopMapper;
import com.dcm.seckill.entity.SeckillShopEntity;
import com.dcm.seckill.service.SeckillShopService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author 牛浩
 */
@Service
public class SeckillShopServiceImpl implements SeckillShopService{
    @Autowired
    private SeckillShopMapper seckillShopMapper;
    @Override
    public List<SeckillShopEntity> findAll() {
        return seckillShopMapper.findAll();
    }

    @Override
    public void add(SeckillShopEntity miaoOrder) throws MyException {
        checkMiaoOrder(miaoOrder);
        miaoOrder.setCreateDate(new Date());
        seckillShopMapper.add(miaoOrder);
    }

    @Override
    public List<SeckillShopEntity> search(Integer state, String configure, Long id) {
        if (state ==null){
            throw new MyException(Constants.SecKillErrorMsg.KILL_STATE_CANNOT_NULL);
        }
        if (configure == null || "".equals(configure)){
            throw new MyException(Constants.SecKillErrorMsg.KILL_CONFIGURE_CANNOT_NULL);
        }
        if (id == null){
            throw new MyException(Constants.SecKillErrorMsg.KILL_MID_CANNOT_NULL);
        }
        return seckillShopMapper.search(state,configure,id);
    }

    @Override
    public SeckillShopEntity findOne(Long id) {
        if (id == null){
            throw new MyException(Constants.SecKillErrorMsg.KILL_MID_CANNOT_NULL);
        }
        return seckillShopMapper.findOne(id);
    }

    @Override
    public int decrNumberById(Long id) {
        if (id == null){
            throw new MyException(Constants.SecKillErrorMsg.KILL_MID_CANNOT_NULL);
        }
        SeckillShopEntity one = findOne(id);
        one.setLimitedSurplus(one.getLimitedSurplus()-1);
        int i = seckillShopMapper.decrNumberById(id);
        return i;
    }


    private static void checkMiaoOrder(SeckillShopEntity miaoOrder) throws MyException {
        if (StringUtils.isBlank(miaoOrder.getActivityIntroduction())){
            throw new MyException(Constants.SecKillErrorMsg.KILL_INTRODUCTION_CANNOT_NULL);
        }
        if (StringUtils.isBlank(miaoOrder.getConfigure())){
            throw new MyException(Constants.SecKillErrorMsg.KILL_CONFIGURE_CANNOT_NULL);
        }
        if (StringUtils.isBlank(miaoOrder.getImg())){
            throw new MyException(Constants.SecKillErrorMsg.KILL_IMG_CANNOT_NULL);
        }
        if (StringUtils.isBlank(miaoOrder.getActivityTitle())){
            throw new MyException(Constants.SecKillErrorMsg.KILL_TITLE_CANNOT_NULL);
        }

    }

}
